package com.wx.push.subscription.push.mybatisplus.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wx.push.subscription.push.mybatisplus.entity.SendMsg;
import com.wx.push.subscription.push.mybatisplus.entity.UserInfo;
import com.wx.push.subscription.push.mybatisplus.service.ISendMsgService;
import com.wx.push.subscription.push.mybatisplus.service.IUserInfoService;
import com.wx.push.subscription.push.vo.Result;
import com.wx.push.subscription.push.vo.UserInfoVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author phil
 * @since 2022-08-22
 */
@RestController
@RequestMapping("/userInfo")
public class UserInfoController {

    @Autowired
    private IUserInfoService userService;
    @Autowired
    private ISendMsgService sendMsgService;

    @PostMapping("/edit")
    public Result editUser(@RequestBody UserInfoVo userInfoVo){
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(userInfoVo,userInfo);
        userInfo.setUpdateTime(LocalDateTime.now());

        boolean isUpdate = userService.update(userInfo,new QueryWrapper<UserInfo>().eq("user_name", userInfo.getUserName()));
        if (isUpdate) {
            return Result.ok();
        }else {
            return Result.fail("更新失败");
        }
    }

    @PostMapping("/add")
    public Result addUser(@RequestBody UserInfoVo userInfoVo){
        if(StringUtils.isEmpty(userInfoVo.getOpenId()) || StringUtils.isEmpty(userInfoVo.getUserName())){
            return Result.fail("OpenId 或 UserName为空");
        }
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(userInfoVo,userInfo);
        if(StringUtils.isEmpty(userInfo.getSendName())){
            userInfo.setSendName(userInfo.getUserName());
        }
        userInfo.setCreateTime(LocalDateTime.now());
        userInfo.setUpdateTime(LocalDateTime.now());
        boolean isInsert = userService.saveOrUpdate(userInfo);
        if (isInsert) {
            UserInfo one = userService.getOne(new QueryWrapper<UserInfo>().eq("open_id", userInfoVo.getOpenId()).orderByDesc("update_time").last("limit 1"));
            SendMsg sendMsg = new SendMsg();
            sendMsg.setSendName(one.getSendName());
            sendMsg.setSendMsg("你没有留言哦~~");
            sendMsg.setUserId(one.getUserId());
            boolean save = sendMsgService.save(sendMsg);
            return Result.ok();
        }else {
            return Result.fail("插入失败");
        }
    }


}